<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          SSM框架学习（五）——MyBatis - 赵先生
        
    </title>

    <link rel="canonical" href="http://zqqpluto.xyz/article/spring-MyBatis/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">

    <link rel="stylesheet" href="/css/donate.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header {
        background-image: url('/img/article_header/article_header.png')
                /*post*/
                
    }

    
</style>

<header class="intro-header">
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#spring"
                                title="spring">spring</a>
                            
                            <a class="tag" href="/tags/#SSM"
                                title="SSM">SSM</a>
                            
                            <a class="tag" href="/tags/#java"
                                title="java">java</a>
                            
                            <a class="tag" href="/tags/#mybatis"
                                title="mybatis">mybatis</a>
                            
                        </div>
                        <h1>SSM框架学习（五）——MyBatis</h1>
                        <h2 class="subheading">spring学习</h2>
                        <span class="meta"  id="busuanzi_container_page_pv" >
                            Posted by 赵先生 on
                            2019-08-16   
                            &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 本文总阅读量<span id="busuanzi_value_page_pv"></span>次
                        </span>

                       

                    </div>
                    


                </div>

            </div>
        </div>
    </div>
</header>
	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">赵先生</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/archive/">Archives</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/about/">About</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/tags/">Tags</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <blockquote>
<p>mybatis学习</p>
</blockquote>
<h1 id="一mybatis">一.Mybatis</h1>
<h2 id="11-mybatis简介">1.1 Mybatis简介</h2>
<blockquote>
<p>Mybatis支持SQL查询、存储过程和高级映射的持久层框架，MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果检索，Mybatis使用简单的XML或注解用于配置和映射，将接口和java的pojo	映射成数据库记录。</p>
</blockquote>
<h2 id="12-mybatis功能层次结构">1.2 Mybatis功能层次结构</h2>
<p><img src="//zqqpluto.xyz/article/spring-MyBatis/2019081316265099.png" alt="Mybatis功能结构层次图"></p>
<ol>
<li>API接口层：<strong>提供外部使用的接口API</strong>，开发人员通过这些API来操作数据库，接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。</li>
<li>数据处理层：<strong>负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理</strong>。它主要的目的是根据调用请求完成一次数据库的操作。</li>
<li>基础支撑层：<strong>负责最基本的功能支撑</strong>，包括连接管理、事务管理、配置加载和缓存处理等，将他们抽取出来作为最基本的组件，为上层的数据处理层提供最基础的支撑。</li>
</ol>
<h2 id="13-mybatis核心部件">1.3 Mybatis核心部件</h2>
<table>
<thead>
<tr>
<th>核心部件</th>
<th>作用</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Configuration</strong></td>
<td>Mybatis所有的配置信息都保存在Configuration对象之中，配置文件中的大部门配置都会存储在改类中</td>
</tr>
<tr>
<td><strong>SqlSession</strong></td>
<td>作为Mybatis工作的主要顶层API，表示和数据库交互时的会话，完成必要数据库的增删查改功能</td>
</tr>
<tr>
<td><strong>Executor</strong></td>
<td>Mybatis执行器，是Mybatis调度核心，负责SQL语句的生成和查询缓存的维护，由它来实现真正对数据库是操作</td>
</tr>
<tr>
<td><strong>StatementHandler</strong></td>
<td>封装了JDBC Statement操作，负责对JDBC Statement的操作，如参数设置等</td>
</tr>
<tr>
<td><strong>ParamentHnadler</strong></td>
<td>负责对用户传递到参数转换成JDBC Statement所对应的数据类型</td>
</tr>
<tr>
<td><strong>ResultHandler</strong></td>
<td>负责将JDBC返回的ResultSet结果集对象转换成List类型集合</td>
</tr>
<tr>
<td><strong>Type Handler</strong></td>
<td>负责java数据类型和jdbc数据类型之间的转化和映射</td>
</tr>
<tr>
<td><strong>MappedStatement</strong></td>
<td>维护一条select、update、delete、insert节点的封装</td>
</tr>
</tbody>
</table>
<h2 id="14-mybatis工作流程">1.4 Mybatis工作流程</h2>
<ol>
<li>加载配置——配置方式主要有两种，一种是XML文件配置，另一种是java代码注解，Mybatis将sql配置信息加载成为一个个MappedStatement对象（包括了传入参数映射配置，执行sql事务语句，结果隐射配置），将其存储发哦内存中。</li>
<li>SQL解析——当API接口层接收到调用请求时，会接受传入sql的id和传入对象（可以是Map，javabean或基本数据类型），Mybatis会根据SQL的id查找到相应的MappedStatement，然后根据传入的参数对象对Mapped Statement对象进行解析，解析后便得到最终需要执行的sql语句和参数。</li>
<li>SQL执行——将最终的sql和参数拿到数据库进行执行，得到需要的结果</li>
<li>结果映射——将操作得到的数据库的结果按照映射配置进行转换，可以将其转换成HashMap，javabean或者基本数据类型，并将最终结果返回。</li>
</ol>
<hr>
<h1 id="二mybatis搭建">二.Mybatis搭建</h1>
<ol>
<li>导入jar包</li>
</ol>
<blockquote>
<ul>
<li>mybatis-3.4.5.jar</li>
<li>mysql-connector-java-5.1.7-bin-jar<br>
百度网盘下载地址：<a href="https://pan.baidu.com/s/1mSQbUeOxpwGyUdISDRlx4Q" target="_blank" rel="noopener">点击下载</a><br>
git下载地址：<a href="https://github.com/huweihuang/spring_jar.git" target="_blank" rel="noopener">点击下载</a></li>
</ul>
</blockquote>
<ol start="2">
<li>书写相信的bean和DAO接口<br>
UserBean</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> userId;</span><br><span class="line">	<span class="keyword">private</span> String userName;</span><br><span class="line">	<span class="keyword">private</span> String password;</span><br><span class="line">	<span class="keyword">private</span> String info;</span><br><span class="line">	<span class="comment">//省略get和set方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DAO接口（操作数据库的方法）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDAO</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">getAll</span><span class="params">()</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//@Param映射文件使用的名字</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> User <span class="title">getUserById</span><span class="params">(@Param(<span class="string">"uId"</span>)</span> <span class="keyword">int</span> userId)</span>;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">addUser</span><span class="params">(User user)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">getByName</span><span class="params">(String search)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>资源配置文件（mybatis-config.xml）——指定数据库连接参数和框架参数</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span><br><span class="line"><span class="meta">&lt;!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"</span></span><br><span class="line"><span class="meta">         "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 配置数据库环境 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">"test"</span>&gt;</span>  <span class="comment">&lt;!-- 默认环境选择test --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!--两个允许环境一个属于测试环境，一个属于正式上线的环境--&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">"test"</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- 配置事务 --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">"JDBC"</span>&gt;</span><span class="tag">&lt;/<span class="name">transactionManager</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- 配置数据源,不适用连接池 --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">"UNPOOLED"</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/javaweb_day7"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"123456"</span>/&gt;</span></span><br><span class="line">			<span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">		</span><br><span class="line">		<span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">"main"</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- 配置事务 --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">"JDBC"</span>&gt;</span><span class="tag">&lt;/<span class="name">transactionManager</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- 配置数据源,不适用连接池 --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">"UNPOOLED"</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/javaday_7?characterEncoding=utf8"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"123456"</span>/&gt;</span></span><br><span class="line">			<span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 配置DAO映射文件 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">"mapper/UserMapper.xml"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="4">
<li>映射配置文件（UserMapper.xml）——用于定义sql语句和映射信息</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span><br><span class="line"><span class="meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"      "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"cn.goktech.dao.UserDAO"</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">	增删改查</span></span><br><span class="line"><span class="comment">	id指定方法名</span></span><br><span class="line"><span class="comment">	resultType:返回值类型，集合写直属子元素类型;</span></span><br><span class="line"><span class="comment">	parameterType:指定参数类型，多参数可写类类型</span></span><br><span class="line"><span class="comment">	 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"getAll"</span> <span class="attr">resultMap</span>=<span class="string">"userMap"</span> &gt;</span></span><br><span class="line">		select * from user</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"getUserById"</span> <span class="attr">resultMap</span>=<span class="string">"userMap"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span>&gt;</span></span><br><span class="line">		select * from user where userId=#&#123;uId&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">	模糊查询，$&#123;&#125;和#&#123;&#125;的区别：</span></span><br><span class="line"><span class="comment">	#&#123;&#125;会添加引号，$&#123;&#125;不会默认添加引号，</span></span><br><span class="line"><span class="comment">	$&#123;&#125;容易造成sql注入，$&#123;&#125;一般用于传入数据库对象,比如表明，类名</span></span><br><span class="line"><span class="comment">	s --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"getByName"</span> <span class="attr">resultType</span>=<span class="string">"cn.goktech.entity.User"</span> <span class="attr">parameterType</span>=<span class="string">"String"</span>&gt;</span></span><br><span class="line">		select * from user where userName like '%$&#123;value&#125;%'  <span class="comment">&lt;!--或 like CONCAT('%',#&#123;search&#125;,'%') --&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"addUser"</span> <span class="attr">parameterType</span>=<span class="string">"cn.goktech.entity.User"</span>&gt;</span></span><br><span class="line">		insert into user(userName,password,info) values (#&#123;userName&#125;,#&#123;password&#125;,#&#123;info&#125;)</span><br><span class="line">	<span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- mysql字段与类属性的映射 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">"cn.goktech.entity.User"</span> <span class="attr">id</span>=<span class="string">"userMap"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">		id映射使用id标签，其他使用result</span></span><br><span class="line"><span class="comment">		property是类中的属性字段，</span></span><br><span class="line"><span class="comment">		column是数据库对应的字段</span></span><br><span class="line"><span class="comment">		 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">"userId"</span> <span class="attr">column</span>=<span class="string">"userId"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">"userName"</span> <span class="attr">column</span>=<span class="string">"userName"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">"password"</span> <span class="attr">column</span>=<span class="string">"password"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">"info"</span> <span class="attr">column</span>=<span class="string">"info"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- &lt;delete id=""&gt;&lt;/delete&gt;</span></span><br><span class="line"><span class="comment">	&lt;update id=""&gt;&lt;/update&gt; --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>每一个select、insert、update、delete的id与DAO接口的方法名对应</strong></p>
</blockquote>
<hr>
<h1 id="三mybatis的api">三.Mybatis的API</h1>
<ol>
<li>SqlSessionFactoryBuilder——该对象负责根据配置文件mybatis-config.xml构建SqlSessionFactory实例</li>
<li>SqlSessionFactory——每一个Mybatis的应用程序都将以一个SqlSessionFactory对象为核心，该对象负责构建SqlSession实例</li>
<li>SqlSession——该对象包含了所有执行Sql的操作方法，用来执行已映射的sql语句，不过SqlSession打开数据库，真正执行交互的是Executor,SqlSession对数据库的操作都是通过Executor来完成的，Executor是动态创建的，不需要我们去管理。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用类加载器加载mybatis配置文件，并构建sqlSession工厂</span></span><br><span class="line">InputStream is = Test.class.getClassLoader().getResourceAsStream(<span class="string">"config/mybatis-config.xml"</span>);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(is);</span><br><span class="line"><span class="comment">//获取SqlSession对象</span></span><br><span class="line">SqlSession session = sqlSessionFactory.openSession();</span><br><span class="line"></span><br><span class="line"><span class="comment">//str映射sql的标识字符串，为要执行的方法的全类名，根据这个找到映射文件中对应的sql语句</span></span><br><span class="line">String str = <span class="string">"cn.goktech.dao.UserDAO.getUserById"</span>;</span><br><span class="line"><span class="comment">//执行查询返回一个user对象的sql</span></span><br><span class="line">User user = sqlSession.selectOne(str, <span class="number">1001</span>);</span><br><span class="line">System.out.println(user.getUserName()+<span class="string">"---"</span>+user.getInfo());</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="四mybatis实现curd">四.Mybatis实现CURD</h1>
<ol>
<li>查询</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用类加载器加载mybatis配置文件，并构建sqlSession工厂</span></span><br><span class="line">InputStream is = Test.class.getClassLoader().getResourceAsStream(<span class="string">"config/mybatis-config.xml"</span>);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(is);</span><br><span class="line"><span class="comment">//获取SqlSession对象</span></span><br><span class="line">SqlSession session = sqlSessionFactory.openSession();</span><br><span class="line"></span><br><span class="line">UserDAO userDAO = sqlSession.getMapper(UserDAO.class);</span><br><span class="line"></span><br><span class="line">List&lt;User&gt; uList = userDAO.getAll();</span><br><span class="line"><span class="keyword">for</span> (User u : uList) &#123;</span><br><span class="line">	System.out.println(u.getUserName()+<span class="string">"---"</span>+u.getInfo());</span><br><span class="line">&#125;</span><br><span class="line">		</span><br><span class="line">User user = userDAO.getUserById(<span class="number">1001</span>);</span><br><span class="line">System.out.println(<span class="string">"user.getUserName="</span>+user.getUserName());</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>增加</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 添加用户测试</span></span><br><span class="line">User u1 = <span class="keyword">new</span> User();</span><br><span class="line">u1.setUserName(<span class="string">"Clover"</span>);</span><br><span class="line">u1.setPassword(<span class="string">"123456"</span>);</span><br><span class="line">u1.setInfo(<span class="string">"文艺小青年"</span>);</span><br><span class="line">		</span><br><span class="line"><span class="keyword">int</span> count = userDAO.addUser(u1);</span><br><span class="line">sqlSession.commit();<span class="comment">//提交事务</span></span><br><span class="line">System.out.println(<span class="string">"count="</span>+count);</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="五mybatis的和取值">五.Mybatis的#和$取值</h1>
<ol>
<li>当传入参数为String类型时：</li>
</ol>
<blockquote>
<p><strong>使用#{}方式可以通过#{参数名}或者默认的#{_paramenter}来获取参数值，但是使用${}时，不能直接通过${参数名}来获取，需要通过默认方式${value}来取值</strong></p>
</blockquote>
<ol start="2">
<li>#{}和${}取值的区别：</li>
</ol>
<blockquote>
<ul>
<li><strong>#{}进行参数获取时，会把参数转成字符串，即会自动加上一个引号 ‘ ’</strong><br>
如  select * from bank  where name= #{name} ，传入名字  “ zhangsan”<br>
最终得到的是 ：select * from bank  where name= ‘ zhangsan’</li>
<li><strong>${}是将传入的数据直接显示生成在sql中：</strong><br>
select * from bank  where name= ${value}     传入名字 “zhangsan”<br>
最终得到： select * from bank  where name  =  zhangsan ，<br>
直接运行报错，所以需要我们手动添加  ‘ ‘    ：    select * from bank  where name= ‘ ${value} ’<br>
<strong>但是这样做会带来非常严重的sql注入</strong><br>
比如传入这样的参数：userDAO.getUserIByPsd(&quot;  pwd111 ’ OR ‘1’='1  &quot;)<br>
实际上是    select * from bank  where password= ’ pwd111 ’ OR ‘1’=‘1’</li>
</ul>
</blockquote>
<ol start="3">
<li>${}使用场景</li>
</ol>
<blockquote>
<p>多数情况下我们应该使用#{ }，但是有些时候我们需要使用${}，比如进行动态排序时，根据传入字段排序：<br>
SELECT * FROM bank order by #{ columnName}，比如说按照工资排序，你传入salary这个字段，结果：SELECT * FROM bank order by ‘salary’，这样明显排序时不起作用的，我们需要  SELECT * FROM bank order by  ${ columnName}。所以说 ${ }方式一般用于传入数据库对象，例如传入表名 ，列名这种。</p>
</blockquote>
<ol start="4">
<li>Mybatis多参数映射查询<br>
当sql语句只需要一个参数作为条件时，那么只要通过#{参数名}便可获得该参数值，但是当有多个参数时，这样会出错，解决方法如下：</li>
</ol>
<blockquote>
<ol>
<li>将多个参数传入map，然后#{keyName}取值</li>
<li>将多个参数封装到实体类，然后#{属性名}取值</li>
<li>Mybatis还提供了一个使用注解来参入多个参数的方式，这种方式需要在<strong>接口</strong>的参数上添加**@Param**注解：</li>
</ol>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> UserBean <span class="title">checkLogin</span><span class="params">(@Param(value=<span class="string">"name"</span>)</span>String userName,@<span class="title">Param</span><span class="params">(value=<span class="string">"password"</span>)</span>String  password)</span>;</span><br><span class="line"><span class="comment">//在映射文件中便可以通过 #&#123;name&#125;  #&#123;password&#125; 取出</span></span><br></pre></td></tr></table></figure>
<ol start="5">
<li>模糊查询</li>
</ol>
<blockquote>
<p>模糊查询不能使用#取值的方式,    like  %#{name}% 不能实现模糊查询，使用$取值的方式，like ‘%${value}%‘可以实现，但是一般不适用此方式，一般使用 like concat(’%’,#{name},’%’)的方式进行模糊查询</p>
</blockquote>
<ol start="7">
<li>特别的异常处理</li>
</ol>
<p>在进行增删查改的时候如果在sql语句中有&gt;或&lt;z，则会报错：<br>
The content of elements must consist of well-formed character data or markup<br>
需要在外部添加<!--[CDATA[SQL语句]]-->,如：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id="getEqualName" resultType="Map"&gt;</span><br><span class="line">&lt;![CDATA[</span><br><span class="line"><span class="keyword">SELECT</span> sname,<span class="keyword">COUNT</span>(*) <span class="keyword">num</span> <span class="keyword">FROM</span> student <span class="keyword">GROUP</span> <span class="keyword">BY</span> sname <span class="keyword">HAVING</span> <span class="keyword">COUNT</span>(sname) &gt;<span class="number">1</span></span><br><span class="line">]]&gt;</span><br><span class="line">&lt;/<span class="keyword">select</span>&gt;</span><br></pre></td></tr></table></figure>
<h1 id="六mybatis关系映射">六.Mybatis关系映射</h1>
<ol>
<li>sql和include元素：sql元素可以定义一条sql的一部分，方便后面的sql引用它。如下：</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- sql与include元素 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">"begin"</span>&gt;</span>select * from teacher<span class="tag">&lt;/<span class="name">sql</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"getAll"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">"begin"</span> /&gt;</span></span><br><span class="line">	where tid&gt;1</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="2">
<li>一对一映射<br>
(1). 在实体类添加相应<strong>对象</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">  <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Teacher</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> tid;</span><br><span class="line">	<span class="keyword">private</span> String tname;</span><br><span class="line">	<span class="keyword">private</span> String phone;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> cid;</span><br><span class="line">	<span class="keyword">private</span> Cs cs; <span class="comment">// 测试一对一：一个班主任带一个班</span></span><br><span class="line">	<span class="comment">//省略了get和set方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>(2).在<em>Mapper.xml中使用</em><em>assoaction</em>*标签</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Mybatis级联 --&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 一对一 --&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- resultMap:type结果返回类型 id标签:column指定表中的主键,property指定类中的属性 result标签：普通字段对应 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">"Cs"</span> <span class="attr">id</span>=<span class="string">"cs"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"cid"</span> <span class="attr">property</span>=<span class="string">"cid"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"cname"</span> <span class="attr">property</span>=<span class="string">"cname"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"introduce"</span> <span class="attr">property</span>=<span class="string">"introduce"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">"Teacher"</span> <span class="attr">id</span>=<span class="string">"teacherMap"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"tid"</span> <span class="attr">property</span>=<span class="string">"tid"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"tname"</span> <span class="attr">property</span>=<span class="string">"tname"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"phone"</span> <span class="attr">property</span>=<span class="string">"phone"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"cid"</span> <span class="attr">property</span>=<span class="string">"cid"</span> /&gt;</span>		</span><br><span class="line">	<span class="comment">&lt;!-- 一对一关系映射,property指定属性名，javaType指定属性类型 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">"cs"</span> <span class="attr">resultMap</span>=<span class="string">"cs"</span>/&gt;</span>	</span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"oneToOne"</span> <span class="attr">resultMap</span>=<span class="string">"teacherMap"</span>&gt;</span></span><br><span class="line">	select * from teacher t,cs c  where t.cid=c.cid</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="4">
<li>一对多映射(一个班级对应多个学生)<br>
(1). 在实体类添加相应<strong>集合</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cs</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> cid;</span><br><span class="line">	<span class="keyword">private</span> String cname;</span><br><span class="line">	<span class="keyword">private</span> String introduce;</span><br><span class="line">	<span class="keyword">private</span> List&lt;Student&gt; students;</span><br><span class="line">	<span class="comment">//省略get和set方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>(2).在*Mapper.xml中使用collection标签</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">"Student"</span> <span class="attr">id</span>=<span class="string">"student"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"sid"</span> <span class="attr">property</span>=<span class="string">"sid"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"sname"</span> <span class="attr">property</span>=<span class="string">"sname"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"password"</span> <span class="attr">property</span>=<span class="string">"password"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"score"</span> <span class="attr">property</span>=<span class="string">"score"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"cid"</span> <span class="attr">property</span>=<span class="string">"cid"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">"Cs"</span> <span class="attr">id</span>=<span class="string">"cs"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"cid"</span> <span class="attr">property</span>=<span class="string">"cid"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"cname"</span> <span class="attr">property</span>=<span class="string">"cname"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"introduce"</span> <span class="attr">property</span>=<span class="string">"introduce"</span>/&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 一对多 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">"students"</span> <span class="attr">resultMap</span>=<span class="string">"student"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line">	</span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"oneToMany"</span> <span class="attr">resultMap</span>=<span class="string">"cs"</span>&gt;</span></span><br><span class="line">	select * from cs c,student s where c.cid=s.cid</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="七动态sql语句">七.动态SQL语句</h1>
<ol>
<li>if元素：如果是字符串默认为null，如果是数字，默认为0</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findEmp"</span> <span class="attr">parameterType</span>=<span class="string">"map"</span> <span class="attr">resultType</span>=<span class="string">"Emp"</span>&gt;</span></span><br><span class="line">	SELECT* FROM EMP WHERE dept no=#&#123;deptNo&#125;</span><br><span class="line">	<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"salary!=null"</span>&gt;</span></span><br><span class="line">		AND salary=#&#123;salary&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="2">
<li>choose-when-otherwise只会在多个选项中执行一个</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"search"</span> <span class="attr">parameterType</span>=<span class="string">"Student"</span> <span class="attr">resultType</span>=<span class="string">"Student"</span>&gt;</span></span><br><span class="line">	select * from student where sname like '%$&#123;sname&#125;%'</span><br><span class="line">	<span class="comment">&lt;!-- choose只会进入一个分支 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">choose</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"password!=null"</span>&gt;</span></span><br><span class="line">			and password like '%$&#123;password&#125;%'</span><br><span class="line">		<span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"score!=0"</span>&gt;</span></span><br><span class="line">			and score&gt;#&#123;score&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></span><br><span class="line">			order by sid desc</span><br><span class="line">		<span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">choose</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="3">
<li>where元素：where 元素知道在<strong>至少有一个以上的if元素满足条件时</strong>才去插入“WHERE”子句。而且，<strong>如果最后得到的sql子句是以“AND”或“OR”开头的，where 元素也知道如何将他们去除。</strong></li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 测试where标签,动态拼接条件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"testWhere"</span> <span class="attr">parameterType</span>=<span class="string">"Student"</span> <span class="attr">resultType</span>=<span class="string">"Student"</span>&gt;</span></span><br><span class="line">	select * from student</span><br><span class="line">	<span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"sname!=null"</span>&gt;</span></span><br><span class="line">			sname like CONCAT('%',#&#123;sname&#125;,'%')</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"password!=null"</span>&gt;</span></span><br><span class="line">			and password like '%$&#123;password&#125;%'</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"score!=0"</span>&gt;</span></span><br><span class="line">			and score &gt;#&#123;score&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="4">
<li>set元素：Set元素主要是用在<strong>更新操作</strong>的时候，它的主要功能和where元素相似，主要是在<set>元素所在位置<strong>输出一个set关键字</strong>，而且还可以<strong>去除内容结尾中无关的逗号</strong>。有个set元素我们就可以<strong>动态的更新那些修改了的字段</strong></set></li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> <span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateStudent"</span> <span class="attr">parameterType</span>=<span class="string">"Student"</span>&gt;</span></span><br><span class="line">	update student</span><br><span class="line">	<span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"sname!=null"</span>&gt;</span></span><br><span class="line">			sname=#&#123;sname&#125;,</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"score!=0"</span>&gt;</span></span><br><span class="line">			score=#&#123;score&#125;,</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"password!=null"</span>&gt;</span></span><br><span class="line">			password=#&#123;password&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">	where sid=#&#123;sid&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="5">
<li>trim元素:</li>
</ol>
<blockquote>
<ol>
<li>prefix：可以给Trim元素包裹内容之前加上指定前缀，</li>
<li>suffix：可以给Trim元素包裹内容之后加上某些后缀，</li>
<li>prefixOverrides：可以把Trim元素包含内容的首部某些内容过滤，</li>
<li>suffixOverrides：可以把Trim元素包含内容的尾部的某些内容过滤。</li>
</ol>
</blockquote>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateStudent"</span> <span class="attr">parameterType</span>=<span class="string">"Student"</span>&gt;</span></span><br><span class="line">	update student</span><br><span class="line">	<span class="tag">&lt;<span class="name">trim</span> <span class="attr">prefix</span>=<span class="string">"set"</span> <span class="attr">suffix</span>=<span class="string">"where sid=#&#123;sid&#125;"</span> <span class="attr">suffixOverrides</span>=<span class="string">","</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"sname!=null"</span>&gt;</span></span><br><span class="line">			sname=#&#123;sname&#125;,</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"score!=0"</span>&gt;</span></span><br><span class="line">			score=#&#123;score&#125;,</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"password!=null"</span>&gt;</span></span><br><span class="line">			password=#&#123;password&#125;,</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">trim</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="6">
<li>foreach元素:Foreach元素实现了循环逻辑，可以实现对一个集合的迭代，通常是在构建 IN 条件语句的时候。<strong>Foreach元素一般实现对三种类型数据的遍历：List,  数组array,  Map三种。</strong><br>
元素简介：</li>
</ol>
<blockquote>
<ol>
<li>item（必选）：表示集合中每一个元素进行迭代时的别名。</li>
<li>collection（必选）：表示传入过来的参数的数据类型，如果传入参数为List，则其属性值为list；传入数组则属性值为array；如果传入参数为User对象，而这个User对象有属性 List  xxlist，那么属性值为collection =“xxlist”。Map稍后讲。</li>
<li>index：在 list 和数组中,index 是元素的序号；在 map 中，index 是元素的 key。</li>
<li>open：表示该语句以什么开始</li>
<li>close：表示该语句以什么结束</li>
<li>separator：表示在每次进行迭代之间以什么符号作为分隔符</li>
</ol>
</blockquote>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- forEach元素 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"award"</span> <span class="attr">resultType</span>=<span class="string">"Student"</span>&gt;</span></span><br><span class="line">	select * from student where sid in</span><br><span class="line">	<span class="comment">&lt;!-- collection:1.List写list,2数组写array,3.map写param.values --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">"list"</span> <span class="attr">item</span>=<span class="string">"id"</span> <span class="attr">open</span>=<span class="string">"("</span> <span class="attr">close</span>=<span class="string">")"</span> <span class="attr">separator</span>=<span class="string">","</span>&gt;</span></span><br><span class="line">		#&#123;id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
<hr>
<h1 id="八spring整合mybatis">八.Spring整合Mybatis</h1>
<ol>
<li>创建javaweb项目，将之前教程的jar包全部导入进来</li>
<li>创建相应的DAO和实体类</li>
<li>配置jdbc.properties</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">driver=com.mysql.jdbc.Driver</span><br><span class="line">url=jdbc:mysql://localhost:3306/javaweb</span><br><span class="line">username=root</span><br><span class="line">password=123456</span><br><span class="line">maxIdle=1000</span><br></pre></td></tr></table></figure>
<p>4.配置Spring-mybatis.xml</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:util</span>=<span class="string">"http://www.springframework.org/schema/util"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:mvc</span>=<span class="string">"http://www.springframework.org/schema/mvc"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/beans/spring-beans-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/context/spring-context-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/util</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/util/spring-util-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="tag"><span class="string">		http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">		"</span>&gt;</span></span><br><span class="line">		</span><br><span class="line">	<span class="comment">&lt;!-- 扫描注解配置 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"cn.goktech.*"</span> /&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 扫描RequestMapping注解  --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">mvc:annotation-driven</span>/&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 1.引用本地配置为文件 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">util:properties</span> <span class="attr">id</span>=<span class="string">"jdbc"</span> <span class="attr">location</span>=<span class="string">"classpath:jdbc.properties"</span> /&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!--  2.配置数据源 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">class</span>=<span class="string">"org.apache.commons.dbcp2.BasicDataSource"</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"#&#123;jdbc.driver&#125;"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"#&#123;jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"#&#123;jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"#&#123;jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxActive"</span> <span class="attr">value</span>=<span class="string">"#&#123;jdbc.maxActive&#125;"</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 3.配置sqlSessionFactory，通过Spring 来获取sqlSessionFactory实例,让Spring根据该工出厂实例获取sqlSession  --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"sqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 指定数据源 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 配置mapp.xml文件所在位置 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperLocations"</span> <span class="attr">value</span>=<span class="string">"classpath:mapper/*Mapper.xml"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		</span><br><span class="line">		<span class="comment">&lt;!-- 给包的类注册别名 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"typeAliasesPackage"</span> <span class="attr">value</span>=<span class="string">"cn.goktech.entity"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 4.方式一：配置sqlSessionTemplate操作类</span></span><br><span class="line"><span class="comment">		：  有了sqlSessionFactory以后，我们就开始要获取SqlSession了，</span></span><br><span class="line"><span class="comment">		当mybatis和spring 整合以后， SqlSession都交由SqlSessionTemplate 来管理了，</span></span><br><span class="line"><span class="comment">		所以我们需要创建对应的Bean-</span></span><br><span class="line"><span class="comment">	 --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- &lt;bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"&gt;</span></span><br><span class="line"><span class="comment">		&lt;constructor-arg ref="sqlSessionFactory"&gt;&lt;/constructor-arg&gt;</span></span><br><span class="line"><span class="comment">	&lt;/bean&gt; --&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 4.方式二：MapperFactoryBean 一个dao需要配置一个MapperFactoryBean --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userMapper"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperFactoryBean"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 指定sqlSessionFactory --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlSessionFactory"</span> <span class="attr">ref</span>=<span class="string">"sqlSessionFactory"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!--指定dao接口，MapperFactoryBean自动生成对应接口的动态代理对象，</span></span><br><span class="line"><span class="comment">			 然后我们再将其依赖注入到service中直接使用。</span></span><br><span class="line"><span class="comment">		 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperInterface"</span> <span class="attr">value</span>=<span class="string">"cn.goktech.dao.UserDAO"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span> </span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">	4.方式三：扫描包与包中的注解类</span></span><br><span class="line"><span class="comment">	自动扫描包,将该包中的接口全部作为mapper</span></span><br><span class="line"><span class="comment">	注解标记：annotationClass属性，只扫描带该注解的接口</span></span><br><span class="line"><span class="comment">	 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"cn.goktech.dao"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 只扫描带有特定注解的接口 --&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- &lt;property name="annotationClass" value="cn.goktech.anno.DiyAnnotation"&gt;&lt;/property&gt; --&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">	</span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/article/spring-SSM整合/" data-toggle="tooltip" data-placement="top" title="SSM框架学习（六）——SSM整合">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/article/爬取一周天气预报/" data-toggle="tooltip" data-placement="top" title="Python爬虫入门实战--------一周天气预报爬取">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <br>

                <!--打赏-->
                
                <!--打赏-->

                <br>
                <!--分享-->
                
                    <div class="social-share"  data-wechat-qrcode-helper="" align="center"></div>
                    <!--  css & js -->
                    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">
                    <script src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>
                
                <!--分享-->
                <br>                       
                
                <!-- require APlayer -->
                

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                <!-- disqus comment end -->

                

            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

  
    <style>
      span.toc-nav-number{
        display: none
      }
    </style>
  
    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">Contents</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一mybatis"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">&#x4E00;.Mybatis</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#11-mybatis简介"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">1.1 Mybatis&#x7B80;&#x4ECB;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#12-mybatis功能层次结构"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">1.2 Mybatis&#x529F;&#x80FD;&#x5C42;&#x6B21;&#x7ED3;&#x6784;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#13-mybatis核心部件"><span class="toc-nav-number">1.3.</span> <span class="toc-nav-text">1.3 Mybatis&#x6838;&#x5FC3;&#x90E8;&#x4EF6;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#14-mybatis工作流程"><span class="toc-nav-number">1.4.</span> <span class="toc-nav-text">1.4 Mybatis&#x5DE5;&#x4F5C;&#x6D41;&#x7A0B;</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二mybatis搭建"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">&#x4E8C;.Mybatis&#x642D;&#x5EFA;</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三mybatis的api"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">&#x4E09;.Mybatis&#x7684;API</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#四mybatis实现curd"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">&#x56DB;.Mybatis&#x5B9E;&#x73B0;CURD</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#五mybatis的和取值"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">&#x4E94;.Mybatis&#x7684;#&#x548C;$&#x53D6;&#x503C;</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#六mybatis关系映射"><span class="toc-nav-number">6.</span> <span class="toc-nav-text">&#x516D;.Mybatis&#x5173;&#x7CFB;&#x6620;&#x5C04;</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#七动态sql语句"><span class="toc-nav-number">7.</span> <span class="toc-nav-text">&#x4E03;.&#x52A8;&#x6001;SQL&#x8BED;&#x53E5;</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#八spring整合mybatis"><span class="toc-nav-number">8.</span> <span class="toc-nav-text">&#x516B;.Spring&#x6574;&#x5408;Mybatis</span></a></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#spring" title="spring">spring</a>
                        
                          <a class="tag" href="/tags/#SSM" title="SSM">SSM</a>
                        
                          <a class="tag" href="/tags/#java" title="java">java</a>
                        
                          <a class="tag" href="/tags/#mybatis" title="mybatis">mybatis</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="https://blog.csdn.net/qq_40705355" target="_blank">CSDN Blog 赵先生</a></li>
                    
                        <li><a href="https://github.com/zqqpluto" target="_blank">Github 赵先生</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>








<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: 'ℬ'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>


<!-- chrome Firefox 中文锚点定位失效-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<!-- smooth scroll behavior polyfill  -->
<script type="text/javascript" src="/js/smoothscroll.js"></script>
<script>
        $('#toc').on('click','a',function(a){
            // var isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;
            // console.log(window.navigator.userAgent,isChrome)
                // if(isChrome) {
                    // console.log(a.currentTarget.outerHTML);
                    // console.log($(a.currentTarget).attr("href"));
                    //跳转到指定锚点
                    // document.getElementById(a.target.innerText.toLowerCase()).scrollIntoView(true);
                    document.getElementById($(a.currentTarget).attr("href").replace("#","")).scrollIntoView({behavior: 'smooth' });
                // }
        })  
</script>


    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">


            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">



                
                <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
                <!--Valine 的核心代码库:-->
                <script src="../../js/Valine.min.js"></script>
				<script src="https://cdnjs.loli.net/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                <div class="comment"></div>
                <script>
                    new Valine({
                        // AV 对象来自上面引入av-min.js(老司机们不要开车➳♡゛扎心了老铁)
                        av: AV,
                        el: '.comment', // 
						emoticon_url: 'https://cloud.panjunwen.com/alu',
                        notify: true, // 邮件提醒!!!
                        verify: false, // 验证码
                        app_id: 'aPeCQXmvnRjGpLqsHsTQ38nT-gzGzoHsz', // 这里填写上面得到的APP ID
                        app_key: 'ou0HF5y2Gu9oPP28sFN3ndGt', // 这里填写上面得到的APP KEY
                        placeholder: '欢迎留言评论' // [v1.0.7 new]留言框占位提示文字
						
                    });
					
                </script>
                



                <ul class="list-inline text-center">
                    
                    
                    

                    

                    

                    
                    <li>
                        <a target="_blank" href="https://github.com/zqqpluto">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                    

                    

                </ul>


                <p class="copyright text-muted">

                    
                    <!-- 不蒜子统计 -->
                    <span id="busuanzi_container_site_uv" style='display:none'>
                        本站访客数<span id="busuanzi_value_site_uv"></span>人
                    </span>
                    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
                    

                    Copyright &copy; 赵先生 2019
                    <br>
                    Theme by <a href="http://beantech.org">BeanTech</a>
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span>
                    re-Ported by <a href="https://huweihuang.github.io/">赵先生</a> |
                    <iframe style="margin-left: 2px; margin-bottom:-5px;" frameborder="0" scrolling="0" width="91px"
                        height="20px"
                        src="https://ghbtns.com/github-btn.html?user=huweihuang&repo=hexo-theme-huweihuang&type=star&count=true">
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
        var d = document, t = 'script',
            o = d.createElement(t),
            s = d.getElementsByTagName(t)[0];
        o.src = u;
        if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
        s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>

    // only load tagcloud.js in tag.html
    if ($('#tag_cloud').length !== 0) {
        async("http://zqqpluto.xyz/js/jquery.tagcloud.js", function () {
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: { start: '#bbbbee', end: '#0085a1' },
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>


<!-- <script>

//----自定义js----------------
function createImgEventFullScreen() {
  var imgs = $(".post-container").find("img");
  console.log(imgs);
  for(var i = 0;i < imgs.length;i++) {
    // $(imgs[i]).click(createCover(imgs[i]));
    imgs[i].onclick= function(e) {
      var src = e.srcElement.currentSrc;
      createCover(src)
    }
  }
  function createCover (src) {
    console.log(src);
    var cover = $("<div id='fullScreenCover' class='zhao-cover-img-container'><img class='zhao-cover-img' src='"+src+"'/></div>");
    $("#fullScreenCover").remove();
    $("body").append(cover);
    $("body").addClass("zhao-no-scroll");
    $("#fullScreenCover").click(function(){
      $("#fullScreenCover").remove();
      $("body").removeClass("zhao-no-scroll");
    })
  }
}
setTimeout(function(){
  createImgEventFullScreen();
},1000)


</script> -->


<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
        var $nav = document.querySelector("nav");
        if ($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-XXXXXXXX-X';
    var _gaDomain = 'yoursite';

    // Originial
    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
            m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->

<script>
    // dynamic User by Hux
    var _baId = 'xxx';

    // Originial
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?" + _baId;
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>



<script>
    function createImgEventFullScreen() {
        var imgs = $(".post-container").find("img");
        console.log(imgs);
        for (var i = 0; i < imgs.length; i++) {
            // $(imgs[i]).click(createCover(imgs[i]));
            imgs[i].onclick = function (e) {
                var src = e.srcElement.currentSrc;
                var _this = $(this);
                console.log(_this);
                createCover(src,_this);
            }
        }
        function createCover(src,_this) {
            console.log(_this);
            console.log(src);
            var cover = $("<div id='outerDiv'  style='position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:5;width:100%;height:100%;display:none;'><div id='innerDiv' style='position:absolute;'><img  id='bigImg' style='border:5px solid #fff;' src=''/></div></div>");
            $("#outerDiv").remove();
            $("body").append(cover);
            imgShow("#outerDiv", "#innerDiv", "#bigImg", _this,src);

        }
    }
    function imgShow(outerDiv, innerDiv, bigImg, _this,src) {
        //var src = _this.attr("src"); //获取当前点击的common-img元素中的src属性
        $(bigImg).attr("src", src); //设置#bigImg元素的src属性

        /*获取当前点击图片的真实大小，并显示弹出层及大图*/
        $("<img/>").attr("src", src).load(function () {
            var windowW = $(window).width(); //获取当前窗口宽度
            var windowH = $(window).height(); //获取当前窗口高度
            var realWidth = this.width; //获取图片真实宽度
            var realHeight = this.height; //获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8; //缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

            if (realHeight > windowH * scale) { //判断图片高度
                imgHeight = windowH * scale; //如大于窗口高度，图片高度进行缩放
                imgWidth = imgHeight / realHeight * realWidth; //等比例缩放宽度
                if (imgWidth > windowW * scale) { //如宽度仍大于窗口宽度
                    imgWidth = windowW * scale; //再对宽度进行缩放
                }
            } else if (realWidth > windowW * scale) { //如图片高度合适，判断图片宽度
                imgWidth = windowW * scale; //如大于窗口宽度，图片宽度进行缩放
                imgHeight = imgWidth / realWidth * realHeight; //等比例缩放高度
            } else { //如果图片真实高度和宽度都符合要求，高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigImg).css("width", imgWidth); //以最终的宽度对图片缩放

            var w = (windowW - imgWidth) / 2; //计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2; //计算图片与窗口上边距
            $(innerDiv).css({ "top": h, "left": w }); //设置#innerDiv的top和left属性
            //console.log('****')
            $(outerDiv).fadeIn("fast"); //淡入显示#outerDiv
        });

        $(outerDiv).click(function () { //再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }
    setTimeout(function () {
        createImgEventFullScreen();
    }, 1000)


</script>


	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="http://zqqpluto.xyz/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

<!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/clipboard.min.js"></script>  
<script type="text/javascript" src="/js/clipboard-use.js"></script>
</body>

</html>
